package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.redis.cache.SpzxCache;
import com.spzx.product.api.domain.Product;
import com.spzx.product.api.domain.ProductDetails;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.domain.SkuQuery;
import com.spzx.product.api.domain.vo.SkuPriceVo;
import com.spzx.product.api.domain.vo.SkuStockVo;
import com.spzx.product.domain.SkuStock;
import com.spzx.product.mapper.ProductMapper;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.service.ProductDetailsService;
import com.spzx.product.service.ProductService;
import com.spzx.product.service.ProductSkuService;
import com.spzx.product.service.SkuStockService;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 商品 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2024-10-26
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Autowired
    private ProductSkuService productSkuService;

    @Autowired
    private SkuStockService skuStockService;

    @Autowired
    private ProductDetailsService productDetailsService;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private ProductSkuMapper productSkuMapper;

    @Override
    public List<Product> getPageList(Product product) {
        return baseMapper.getPageList(product);
    }

    @Override
    public int saveProduct(Product product) {
        //调用自带的方法保存商品信息
        baseMapper.insert(product);
        //获取商品SKU信息
        List<ProductSku> productSkuList = product.getProductSkuList();
        //创建保存ProductSku对象进行批量保存的地址
        ArrayList<ProductSku> productSkus = new ArrayList<>();
        ArrayList<SkuStock> skuStocks = new ArrayList<>();
        //遍历所有获取的productSku
        for (int i = 0; i < productSkuList.size(); i++) {
            //获取productSku对象
            ProductSku productSku = productSkuList.get(i);
            //设置商品Id
            productSku.setProductId(product.getId());
            //设置sku_code
            productSku.setSkuCode(product.getId() + "_" + i);
            //设置sku_Name
            productSku.setSkuName(product.getName() + "" + productSku.getSkuSpec());
            //设置状态值
            productSku.setStatus(0);
            //将productSku放入到集合中
            productSkus.add(productSku);

        }
        //再批量保存productSku信息
        productSkuService.saveBatch(productSkus);

        //遍历所有的sku_stock信息
        for (int i = 0; i < productSkuList.size(); i++) {
            //获取ProductSku
            ProductSku productSku = productSkuList.get(i);
            //创建stock对象
            SkuStock skuStock = new SkuStock();
            //设置skuid
            skuStock.setSkuId(productSku.getId());
            //设置状态值
            skuStock.setStatus(0);
            //获取商品的库存
            Integer stockNum = productSku.getStockNum();
            //设置可用的库存数量
            skuStock.setAvailableNum(stockNum);
            //设置总的库存数量
            skuStock.setTotalNum(stockNum);
            //设置锁定的库存数量
            skuStock.setLockNum(0);
            //将skuStock对象添加到集合中
            skuStocks.add(skuStock);
        }
        skuStockService.saveBatch(skuStocks);

        //获取商品的图片详情
        List<String> detailsImageUrlList = product.getDetailsImageUrlList();
        //将商品以字符串并以逗号分隔保存
        String join = String.join(",", detailsImageUrlList);
        //创建ProductDetail对象
        ProductDetails productDetails = new ProductDetails();
        //设置商品id
        productDetails.setProductId(product.getId());
        //设置图片地址
        productDetails.setImageUrls(join);
        //保存图片详情
        productDetailsService.save(productDetails);
        return 1;
    }


    /*
     * 根据Id更新信息
     * */
    @Override
    public void updateProductById(Product product) {
        //更新商品数据
        baseMapper.updateById(product);
        //更新Sku信息
        //先从product对象获取sku集合
        List<ProductSku> productSkuList = product.getProductSkuList();
        //遍历SKU信息并修改SKU数据和库存信息
        productSkuList.forEach(productSku -> {
            //更新SKU信息
            productSkuService.updateById(productSku);
            //更新库存
            //根据skuID查询对应的库存信息
            SkuStock skuStock = skuStockService.getOne(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getSkuId, productSku.getId()));
            //开始修改库存
            skuStock.setTotalNum(productSku.getStockNum());
            skuStock.setAvailableNum(skuStock.getTotalNum() - skuStock.getLockNum());
            skuStockService.updateById(skuStock);
            //修改Details
            //获取修改的Details
            ProductDetails productDetails = productDetailsService.getOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, product.getId()));
            productDetails.setImageUrls(String.join(",", product.getDetailsImageUrlList()));
            productDetailsService.updateById(productDetails);

        });


    }

    /*
     * 根据Id删除商品信息
     * */
    @Override
    public void deleteProductById(List<Long> ids) {
        //删除Product
        baseMapper.deleteBatchIds(ids);
        //获取Sku列表
        List<ProductSku> productSkuList = productSkuService.list(new LambdaQueryWrapper<ProductSku>().in(ProductSku::getProductId, ids)
                .select(ProductSku::getId));
        //遍历SKU列表
        productSkuList.forEach(productSku -> {
            productSkuService.removeById(productSku.getId());
            skuStockService.remove(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getSkuId, productSku.getId()));
        });
        //删除Details
        productDetailsService.remove(new LambdaQueryWrapper<ProductDetails>().in(ProductDetails::getProductId, ids));
    }

    @Override
    public void updateAuditStatus(Long id, Integer auditStatus) {
        Product product = new Product();
        product.setId(id);
        if (auditStatus == 1) {
            product.setAuditStatus(1);
            product.setAuditMessage("审核通过");
        } else {
            product.setAuditStatus(-1);
            product.setAuditMessage("审核不通过");
        }
        baseMapper.updateById(product);
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        if (status != 1 && status != -1)
            throw new ServiceException("非法值");
        Product product = new Product();
        product.setId(id);
        product.setStatus(status);
        baseMapper.updateById(product);
        //更新SKU的状态
        List<ProductSku> productSkuList = productSkuService.list(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id));
        //遍历
        productSkuList.forEach(productSku -> {
            //判断状态值并根据状态值为上架的添加到布隆过滤器
            if (status == 1) {
                RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter("sku:bloom:filter");
                bloomFilter.add(productSku.getId());
            }
            productSku.setStatus(status);
            productSkuService.updateById(productSku);
        });


    }

    @Override
    public List<ProductSku> getTopProductSku() {
        return baseMapper.getTopProductSku();
    }

    @Override
    public List<ProductSku> selectProductSkuList(SkuQuery skuQuery) {
        return baseMapper.selectProductSkuList(skuQuery);
    }

//    @SpzxCache(prefix = "skuPriceVo:")
    @Override
    public SkuPriceVo getSkuPriceVoBySkuId(Long skuId) {
        //调用Sku自带的方法获取Sku信息
        ProductSku productSku = productSkuService.getById(skuId);
        //创建SkuPriceVo容器
        SkuPriceVo skuPriceVo = new SkuPriceVo();
        //再通过set和get方法给SkuPriceVo赋值
        skuPriceVo.setSkuId(skuId);
        skuPriceVo.setSalePrice(productSku.getSalePrice());
        skuPriceVo.setMarketPrice(productSku.getMarketPrice());
        return skuPriceVo;
    }

    @SpzxCache(prefix = "productDetails:")
    @Override
    public ProductDetails getProductDetails(Long id) {
        //调用自带方法获取属性
        ProductDetails productDetails = productDetailsService.getOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, id));
        return productDetails;
    }

//    @SpzxCache(prefix = "skuSpecValue:")
    @Override
    public Map<String, Long> getSkuSpecValue(Long id) {
        //首先只能根据参数的商品ID获取Sku信息
//        List<ProductSku> productSkuList = productSkuService.list(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id));
        List<ProductSku> productSkuList = productSkuMapper.selectList(
                new LambdaQueryWrapper<ProductSku>()
                        .eq(ProductSku::getProductId, id)
                        .select(ProductSku::getId, ProductSku::getSkuSpec));
        //创建返回的Map集合
        Map<String, Long> returnMap = new HashMap<>();
        //遍历Sku给响应数据赋值
        productSkuList.forEach(productSku -> {
            returnMap.put(productSku.getSkuSpec(), productSku.getId());
        });
        return returnMap;
    }

    @Override
    public SkuStockVo getSkuStock(Long skuId) {
        //根据sku的id获取skuStock
        SkuStock skuStock = skuStockService.getOne(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getSkuId, skuId));
        //创建SkuStockVo容器
        SkuStockVo skuStockVo = new SkuStockVo();
        //因为SkuStockVo里的属性和SkuStock里包含的属性名相同,可以使用复制
        BeanUtils.copyProperties(skuStock, skuStockVo);
        return skuStockVo;
    }

    @SpzxCache(prefix = "product:")
    @Override
    public Product getProductInfoById(Long id) {
        return baseMapper.selectById(id);
    }

    @SpzxCache(prefix = "productSku:")
    @Override
    public ProductSku getProductSkuById(Long skuId) {
        ProductSku productSku = productSkuService.getById(skuId);
        productSku.setSkuId(skuId);
        return productSku;
    }

    @Override
    public Product getProductById(Long id) {
        //获取Product对象
        Product product = this.getById(id);
        //将商品Sku信息设置到商品中
        List<ProductSku> productSkuList = productSkuService.list(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id));
        //遍历所有的sku信息
        productSkuList.forEach(productSku -> {
            //根据skuId查询库存表获取库存对象
            SkuStock skuStock = skuStockService.getOne(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getSkuId, productSku.getId()));
            //设置商品库存
            productSku.setStockNum(skuStock.getTotalNum());
        });

        //将Sku信息设置到商品中
        product.setProductSkuList(productSkuList);
        //根据商品id获取图片详情
        ProductDetails productDetails = productDetailsService.getOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, id));
        //获取图片详情地址
        String imageUrls = productDetails.getImageUrls();
        //将图片详情地址转换为数组
        String[] split = imageUrls.split(",");
        //将数组转换成集合
        List<String> productDetailsList = Arrays.asList(split);
        //将集合存入商品中
        product.setDetailsImageUrlList(productDetailsList);


        return product;
    }


}
